package com.x.provider.customer.factory.dto.impl;

import com.x.core.utils.BeanUtil;
import com.x.provider.api.customer.model.dto.directory.AttributeDTO;
import com.x.provider.api.customer.model.dto.directory.AttributeValueDTO;
import com.x.provider.customer.factory.dto.DirectoryDTOFactory;
import com.x.provider.customer.model.domain.directory.Attribute;
import com.x.provider.customer.model.domain.directory.AttributeValue;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DirectoryDTOFactoryImpl implements DirectoryDTOFactory {

    @Override
    public List<AttributeDTO> prepare(List<Attribute> attributeList, List<AttributeValue> attributeValueList) {
        if (attributeList.isEmpty()){
            return new ArrayList<>();
        }
        Map<Long, List<AttributeValue>> attributeValueMap = attributeValueList.stream().collect(Collectors.groupingBy(item -> item.getAttributeId()));
        List<AttributeDTO> result = new ArrayList<>(attributeList.size());
        attributeList.stream().forEach(item -> {
            AttributeDTO attributeDTO = BeanUtil.prepare(item, AttributeDTO.class);
            attributeDTO.setAttributeValueList(BeanUtil.prepare(attributeValueMap.get(item.getId()), AttributeValueDTO.class));
            result.add(attributeDTO);
        });
        return result;
    }

}
